<?php

namespace app\admin\controller;

use think\Controller;
use app\admin\model\Admin as AdminModel;
use app\admin\model\Group as GroupModel;
use app\admin\validate\Admin as AdminValidate;
use app\admin\model\Info as InfoModel;

class Login extends Controller
{
    protected $AdminModel;
    protected $AdminValidate;
    protected $GroupModel;
    protected $InfoModel;

    protected function initialize()
    {
        $this->AdminModel = new AdminModel();
        $this->AdminValidate = new AdminValidate();
        $this->GroupModel = new GroupModel();
        $this->InfoModel = new InfoModel();
    }

    public function index()
    {
        if (request()->isPost()) {
            $data = input();
            $isLogin = $this->AdminModel->CheckData($data);
            if ($isLogin) {
                $this->success('登录成功！', 'index/index');
            } else {
                $this->error('用户名或者密码错误,请重试');
            }
        }

        return view();
    }

    public function logout()
    {
        session(null);
        $this->success('退出成功!', 'login/index');
    }

    public function reg()
    {
        if (request()->isPost()) {
            $data = input();
            $groupData = [
                'company_name' => $data['company_name'],
                'company_contact' => $data['company_contact'],
                'company_phone' => $data['company_phone'],
            ];
            $groupRes = $this->GroupModel->create($groupData);
            $infoData = [
                'gid' => $groupRes->id,
                'title' => $data['company_name'],
                'tel' => $data['company_phone'],
            ];
            $this->InfoModel->save($infoData);
            $adminData = [
                'gid' => $groupRes->id,
                'name' => $data['name'],
                'password' => $data['password'],
                'is_admin' => 1,
            ];
            if (!$this->AdminValidate->scene('add')->check($adminData)) {
                $this->error($this->AdminValidate->getError());
            }
            $adminRes = $this->AdminModel->create($adminData);
            if ($adminRes) {
                session('adminId', $adminRes->id);
                session('adminGid', $adminRes->gid);
                session('adminName', $adminRes->name);
                $this->success('注册成功！', 'index/index');
            } else {
                $this->error('用户名或者密码错误,请重试');
            }
        }

        return view();
    }
}
